from typing import Optional
from sqlalchemy.orm import Session

from ..crud.base import CRUDBase
from ..models.student import Student
from ..schemas.student import StudentCreate, StudentUpdate

class CRUDStudent(CRUDBase[Student, StudentCreate, StudentUpdate]):
    def get_by_user_id(self, db: Session, *, user_id: int) -> Optional[Student]:
        """通过用户ID获取学生"""
        return db.query(Student).filter(Student.user_id == user_id).first()

    def create_with_user(
            self, db: Session, *, obj_in: StudentCreate, user_id: int
    ) -> Student:
        """创建与用户关联的学生"""
        obj_in_data = obj_in.model_dump()
        db_obj = Student(**obj_in_data, user_id=user_id)
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

student_crud = CRUDStudent(Student)